import 'dart:convert';
import 'dart:ui' as prefix0;

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:dio/dio.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../util/SignUtil.dart';
import '../../util/AppSaveInfoUtil.dart';

class ChooseCoupon extends StatefulWidget {
  String goods_id;
  List<String> ids;
  ChooseCoupon({Key key, this.goods_id, this.ids}) : super(key: key);

  @override
  _ChooseCouponState createState() => _ChooseCouponState();
}

class _ChooseCouponState extends State<ChooseCoupon> {
  EasyRefreshController _controller = new EasyRefreshController();
  String token;
  int page = 1;
  List coupons = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text(
          "可使用优惠券",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        actions: <Widget>[
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
              child: Text(
                '不使用优惠券',
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE),
                    color: Colors.black54),
              ),
            ),
            onTap: () {
              Map coupon = new Map();
              coupon['money'] = '0';
              coupon['coupon_record_id'] = "";
              Navigator.of(context).pop(coupon);
            },
          )
        ],
      ),
      body: Container(
        child: EasyRefresh(
          controller: _controller,
          enableControlFinishLoad: true,
          enableControlFinishRefresh: true,
          onLoad: () {
            page++;
          },
          onRefresh: () {
            page = 1;
          },
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return renderRow(context, index);
            },
            itemCount: coupons.length,
          ),
        ),
      ),
    );
  }

  Widget renderRow(BuildContext context, int index) {
    return GestureDetector(
        onTap: () {
          Navigator.of(context).pop(coupons[index]);
        },
        child: Container(
          margin: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
              0),
          // padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
          decoration: BoxDecoration(
              color: white,
              borderRadius: BorderRadius.circular(
                  ScreenUtil.getInstance().setHeight(DP_10))),
          child: Stack(
            children: <Widget>[
              Container(
                height: kMargin140 * 1.4,
                // padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
                child: Row(
                  children: <Widget>[
                    Container(
                      width: kMargin140 * 1.4,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage("images/quan_bg_miane.png"),
                          fit: BoxFit.fill,
                        ),
                      ),
                      // quan_bg_miane
                      child: Column(
                        children: <Widget>[
                          Container(
                            height: ScreenUtil.getInstance().setWidth(DP_40),
                          ),
                          Text(MONEY + coupons[index]['money'],
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(BIG_FONT_SIZE * 1.2),
                                  // fontWeight: FontWeight.bold,
                                  color: white)),
                          Container(
                            height: ScreenUtil.getInstance().setWidth(DP_8),
                          ),
                          Text(
                              coupons[index]['condition_money'] == '0'
                                  ? '无门槛使用'
                                  : '满' +
                                      coupons[index]['condition_money'] +
                                      '元可用',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(MINI_FONT_SIZE),
                                  color: white)),
                        ],
                      ),
                    ),
                    Container(
                      width: ScreenUtil.getInstance().setWidth(DP_60),
                    ),
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          height: ScreenUtil.getInstance().setWidth(DP_30),
                        ),
                        Text(coupons[index]['name'],
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(BIG_FONT_SIZE),
                                color: black)),
                        Container(
                          height: ScreenUtil.getInstance().setWidth(DP_15),
                        ),
                        Text(
                            '有效期:' +
                                coupons[index]['use_start_time'] +
                                '至' +
                                coupons[index]['use_end_time'],
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(MINI_FONT_SIZE),
                                color: black_99)),
                      ],
                    )),
                  ],
                ),
              ),
              //  Positioned(
              //         right: ScreenUtil.getInstance().setHeight(DP_20),
              //         top: 10,
              //         bottom: 10,
              //         child: Image.asset(
              //                 "images/coupon_expried.png",
              //                 scale: 1.2,
              //               ))
            ],
          ),
        ));
  }

  @override
  void initState() {
    getString(TOKEN).then((value) {
      token = value;
      getList();
    });

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future getList() async {
    //优惠券列表
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_COUPON_VIABLELIST),
      'token': token,
      'goods_id': widget.goods_id.toString()
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_COUPON_VIABLELIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        coupons.clear();
        _controller.finishRefresh();
        List temp = userMap['data']['list'];
        bool has = false;
        for (int i = 0; i < temp.length; i++) {
          has = false;
          if (widget.ids != null) {
            for (int j = 0; j < widget.ids.length; j++) {
              if (widget.ids[j] == temp[i]['coupon_record_id'].toString()) {
                has = true;
                break;
              }
            }
            if (!has) {
              coupons.add(temp[i]);
            }
          } else {
            coupons.add(temp[i]);
          }
        }
      });
    }
  }
}
